const execSQL = require("../../db/mysql");
async function searchProduct(name) {
    try {
        let sql = `SELECT product.*,picture.url,picture.id as pID FROM product,picture where product.id=picture.productID and product.productName like '%${name}%' and picture.desc='商品展示'`
        const data = await execSQL(sql);
        return {
            code: 1,
            msg: '查询成功',
            data:data
        }
    } catch (error) {
        return {
            code: 0,
            msg: '查询失败',
            data:data
        }
    }
}

async function getCategory() {
    try {
        let sql = "select * from productcategory";
        const data = await execSQL(sql);

        return {
            code: "1",
            msg: "获取分类成功",
            result: data,
        };
    } catch (error) {
        return {
            code: "0",
            msg: "获取分类失败",
        };
    }
}
async function getAllProduct() {
    try {
        let sql = "SELECT product.*,picture.url,picture.id as pID FROM product,picture where product.id=picture.productID and picture.desc='商品展示'";
        const data = await execSQL(sql);
        
        return {
            code: 1,
            msg: "请求成功",
            result: data,
        };
    } catch (error) {
        return {
            code: 0,
            msg: "请求失败",
        };
    }
}
async function getDetail(id) {
    try {
        let sql = "SELECT product.*,picture.url as productImg,picture.desc as imgDesc FROM product,picture where product.id=picture.productID and product.id=?";
        let sqlParams = [id];
        const data = await execSQL(sql, sqlParams);
        return {
            code: 1,
            msg: "请求成功",
            result: data,
        };
    } catch (error) {
        return {
            code: 0,
            msg: "请求失败",
        };
    }
}
async function getProductByCategory(id){
    try {
        let sql = "SELECT product.*,picture.url,picture.id as pID FROM product,picture where product.id=picture.productID and categoryID =? and picture.desc='商品展示'";
        let sqlParams = [id];
        const data =                                                            await execSQL(sql, sqlParams);
        return {
            code: 1,
            msg: '请求成功',
            result:data
        }
    } catch (error) {
        return {
            code: 0,
            msg: "请求失败",
        };
    }
}
module.exports = {
    getCategory,
    getAllProduct,
    getDetail,
    getProductByCategory,
    searchProduct
};
